package com.fengyi.library.controller;

import com.fengyi.library.DTO.BookDTO;
import com.fengyi.library.model.Book;
import com.fengyi.library.service.BookService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/books")
public class BookController {

    @GetMapping
    public String redirectToList() {
        return "redirect:/books/list";
    }

    private final BookService bookService;

    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @GetMapping("/list")
    public String listBooks(@RequestParam(defaultValue = "0") int page,
                           @RequestParam(defaultValue = "10") int size,
                           Model model) {
        Page<BookDTO> bookPage = bookService.findAllBooks(
                PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"))
        );
        model.addAttribute("books", bookPage.getContent());
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", bookPage.getTotalPages());
        model.addAttribute("totalItems", bookPage.getTotalElements());
        return "books/list";
    }

    @GetMapping("/search")
    public String searchBooks(@RequestParam(required = false) String keyword,
                             @RequestParam(defaultValue = "0") int page,
                             @RequestParam(defaultValue = "10") int size,
                             Model model) {
        Page<BookDTO> bookPage;
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            bookPage = bookService.searchBooks(
                    keyword, 
                    PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"))
            );
            model.addAttribute("keyword", keyword);
        } else {
            bookPage = bookService.findAllBooks(
                    PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"))
            );
        }
        
        model.addAttribute("books", bookPage.getContent());
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", bookPage.getTotalPages());
        model.addAttribute("totalItems", bookPage.getTotalElements());
        
        return "books/search";
    }
    
    @GetMapping("/detail/{id}")
    public String showBookDetails(@PathVariable Integer id, Model model) {
        BookDTO bookDTO = bookService.findById(id);
        model.addAttribute("book", bookDTO);
        return "books/detail";
    }

    @GetMapping("/view/{id}")
    public String viewBook(@PathVariable Integer id, Model model) {
        // 重定向到detail路径
        return "redirect:/books/detail/" + id;
    }

    @GetMapping("/admin/add")
    public String showAddBookForm(Model model) {
        model.addAttribute("book", new Book());
        return "admin/book-form";
    }

    @PostMapping("/admin/add")
    public String addBook(@Valid @ModelAttribute("book") Book book,
                         BindingResult result,
                         RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            return "admin/book-form";
        }
        
        try {
            // 创建一个新的BookDTO并设置属性
            BookDTO bookDTO = new BookDTO();
            bookDTO.setTitle(book.getTitle());
            bookDTO.setAuthor(book.getAuthor());
            bookDTO.setPublisher(book.getPublisher());
            bookDTO.setPublicationYear(book.getPublicationYear());
            bookDTO.setIsbn(book.getIsbn());
            bookDTO.setCategory(book.getCategory());
            bookDTO.setDescription(book.getDescription());
            bookDTO.setQuantity(book.getQuantity());
            bookDTO.setAvailableQuantity(book.getAvailableQuantity());
            
            bookService.saveBook(bookDTO);
            redirectAttributes.addFlashAttribute("success", "图书添加成功");
            return "redirect:/books/list";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "添加图书失败: " + e.getMessage());
            return "redirect:/books/admin/add";
        }
    }

    @GetMapping("/admin/edit/{id}")
    public String showEditBookForm(@PathVariable Integer id, Model model) {
        BookDTO bookDTO = bookService.findById(id);
        // 创建一个Book对象并从DTO中设置属性
        Book book = new Book();
        book.setId(bookDTO.getId());
        book.setTitle(bookDTO.getTitle());
        book.setAuthor(bookDTO.getAuthor());
        book.setPublisher(bookDTO.getPublisher());
        book.setPublicationYear(bookDTO.getPublicationYear());
        book.setIsbn(bookDTO.getIsbn());
        book.setCategory(bookDTO.getCategory());
        book.setDescription(bookDTO.getDescription());
        book.setQuantity(bookDTO.getQuantity());
        book.setAvailableQuantity(bookDTO.getAvailableQuantity());
        book.setCreatedAt(bookDTO.getCreatedAt());
        book.setUpdatedAt(bookDTO.getUpdatedAt());
        
        model.addAttribute("book", book);
        return "admin/book-form";
    }

    @PostMapping("/admin/edit/{id}")
    public String updateBook(@PathVariable Integer id,
                            @Valid @ModelAttribute("book") Book book,
                            BindingResult result,
                            RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            return "admin/book-form";
        }
        
        try {
            // 创建一个BookDTO并设置属性
            BookDTO bookDTO = new BookDTO();
            bookDTO.setId(id);
            bookDTO.setTitle(book.getTitle());
            bookDTO.setAuthor(book.getAuthor());
            bookDTO.setPublisher(book.getPublisher());
            bookDTO.setPublicationYear(book.getPublicationYear());
            bookDTO.setIsbn(book.getIsbn());
            bookDTO.setCategory(book.getCategory());
            bookDTO.setDescription(book.getDescription());
            bookDTO.setQuantity(book.getQuantity());
            bookDTO.setAvailableQuantity(book.getAvailableQuantity());
            bookDTO.setCreatedAt(book.getCreatedAt());
            bookDTO.setUpdatedAt(book.getUpdatedAt());
            
            bookService.saveBook(bookDTO);
            redirectAttributes.addFlashAttribute("success", "图书更新成功");
            return "redirect:/books/list";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "更新图书失败: " + e.getMessage());
            return "redirect:/books/admin/edit/" + id;
        }
    }

    @PostMapping("/admin/delete/{id}")
    public String deleteBook(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        try {
            bookService.deleteBook(id);
            redirectAttributes.addFlashAttribute("success", "图书删除成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除图书失败: " + e.getMessage());
        }
        return "redirect:/books/list";
    }
}
